//
//  HttpRequest.m
//  Friendsback
//
//  Created by 宋质彬 on 2018/3/7.
//  Copyright © 2018年 宋质彬. All rights reserved.
//

#import "HttpRequest.h"

@implementation HttpRequest

+ (AFHTTPSessionManager *)sharedManager

{
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        
        manager = [AFHTTPSessionManager manager];
        //最大请求并发任务数
        manager.operationQueue.maxConcurrentOperationCount = 5;
        
        // 请求格式
        // AFHTTPRequestSerializer            二进制格式
        // AFJSONRequestSerializer            JSON
        // AFPropertyListRequestSerializer    PList(是一种特殊的XML,解析起来相对容易)
        
        manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 上传普通格式
        
        // 超时时间
        manager.requestSerializer.timeoutInterval = 30.0f;
        // 设置请求头
        [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
        // 设置接收的Content-Type
        manager.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/html", @"application/json",@"text/plain",nil];
        
        // 返回格式
        // AFHTTPResponseSerializer           二进制格式
        // AFJSONResponseSerializer           JSON
        // AFXMLParserResponseSerializer      XML,只能返回XMLParser,还需要自己通过代理方法解析
        // AFXMLDocumentResponseSerializer (Mac OS X)
        // AFPropertyListResponseSerializer   PList
        // AFImageResponseSerializer          Image
        // AFCompoundResponseSerializer       组合
        
        manager.responseSerializer = [AFJSONResponseSerializer serializer];//返回格式 JSON
        //设置返回C的ontent-type
        manager.responseSerializer.acceptableContentTypes=[[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/html", @"application/json",@"text/plain",nil];
        
        
        
    
        
    });
    
    // 设置token
    NSString *userToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    if (userToken.length!=0) {
        if ([JSLKitFactory isNotNull:userToken]) {
            [manager.requestSerializer setValue:userToken forHTTPHeaderField:@"x-access-phone"];
        }
        
    }
    
    
    return manager;
}



// 判断网络
+ (void)judgeNetworkStatusWithSuccess:(void(^)(AFNetworkReachabilityStatus status))success
{
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
//    __weak typeof(self) weakSelf = self;
    

    //监听改变
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (success) {
            success(status);
        }
        
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable: {
                [JSLKitFactory showHUDWithMessage:@"网络不可用"];
                NSLog(@"网络不可用");
                break;
            }
                
            case AFNetworkReachabilityStatusReachableViaWiFi: {
                //                [weakSelf loadMessage:@"Wifi已开启"];
                NSLog(@"Wifi已开启");
                break;
            }
                
            case AFNetworkReachabilityStatusReachableViaWWAN: {
                //                [weakSelf loadMessage:@"你现在使用的流量"];
                NSLog(@"你现在使用的流量");
                break;
            }
                
            case AFNetworkReachabilityStatusUnknown: {
                //                [weakSelf loadMessage:@"你现在使用的未知网络"];
//                [JSLKitFactory showHUDWithMessage:@"网络不可用"];
                NSLog(@"你现在使用的未知网络");
                break;
            }
                
            default:
                break;
        }
    }];
    
    //开始监听
    [reachabilityManager startMonitoring];
    
//    // 监听结束
//    [reachabilityManager stopMonitoring];
  
}

#pragma mark - error deal to
+ (void)errorInfoDealToWithTask:(NSURLSessionDataTask * )task {
    
    NSHTTPURLResponse * response = (NSHTTPURLResponse *)task.response;
    NSLog(@"%ld",(long)response.statusCode);
    NSInteger statusCode = response.statusCode;
    
    
    if (statusCode == 401) {
//        [UserManager logout];
        [JSLKitFactory showHUDWithMessage:@"登录异常"];
    } else if (statusCode/100 == 5) {
        [JSLKitFactory showHUDWithMessage:@"异常500"];
        
    } else if (statusCode/100 == 3) {
        [JSLKitFactory showHUDWithMessage:@"异常300"];
    } else if (statusCode ==0) {
    
        [JSLKitFactory showHUDWithMessage:@"网络异常"];
    }else {
        [JSLKitFactory showHUDWithMessage:@"出现异常"];
//        [error localizedDescription];
    }
    
    
}


+ (void)GET_PROGRESS:(NSString *)URLString
parameters:(id)parameters
  progress:(void (^)(NSProgress * downloadProgress))progress
   success:(void(^)(id result,NSString *successMessage))success
   failure:(void(^)(NSInteger code,NSString *errorMessage))failure
//    errors:(void(^)(NSError * _Nonnull error))errors
{
    //创建请求地址
    NSString *URLS= [NSString stringWithFormat:@"%@/%@",Url_Server,URLString];
    //构造参数
    
    //AFN管理者调用get请求方法
    [[HttpRequest sharedManager] GET:URLS parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        //返回请求返回进度
        NSLog(@"downloadProgress-->%@",downloadProgress);
        
        if (progress) {
            progress(downloadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功返回数据 根据responseSerializer 返回不同的数据格式
        NSLog(@"responseObject-->%@",responseObject);
        
        if ([responseObject[@"code"] integerValue] == 0) {
            if (success) {
                success(responseObject[@"result"],responseObject[@"message"]);
            }
        }else{
            if (failure) {
                failure([responseObject[@"code"] integerValue],responseObject[@"message"]);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        NSLog(@"error-->%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self errorInfoDealToWithTask:task];
        });
    }];
}

+ (void)POST_PROGRESS:(NSString *)URLString
parameters:(id)parameters
  progress:(void (^)(NSProgress * uploadProgress))progress
   success:(void(^)(id result,NSString *successMessage))success
   failure:(void(^)(NSInteger code,NSString *errorMessage))failure
//    errors:(void(^)(NSError * _Nonnull error))errors
{
    //创建请求地址
    NSString *URLS= [NSString stringWithFormat:@"%@/%@",Url_Server,URLString];
    //构造参数

    //AFN管理者调用get请求方法
    [[HttpRequest sharedManager] POST:URLS parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
        if (progress) {
            progress(uploadProgress);
        }
        //返回请求返回进度
        NSLog(@"downloadProgress-->%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功返回数据 根据responseSerializer 返回不同的数据格式
        NSLog(@"responseObject-->%@",responseObject);
        
        
        if ([responseObject[@"code"] integerValue] == 0) {
            if (success) {
                success(responseObject[@"result"],responseObject[@"message"]);
            }
        }else{
            if (failure) {
                failure([responseObject[@"code"] integerValue],responseObject[@"message"]);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        NSLog(@"error-->%@",error);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self errorInfoDealToWithTask:task];
        });
    }];
}



+ (void)GET_ERROR:(NSString *)URLString
 parameters:(id)parameters
    success:(void(^)(id result))success
    failure:(void(^)(NSError*error))failure

{
    //创建请求地址
    NSString *URLS= [NSString stringWithFormat:@"%@/%@",Url_Server,URLString];
    //构造参数
    
    //AFN管理者调用get请求方法
    [[HttpRequest sharedManager] GET:URLS parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        //返回请求返回进度
        NSLog(@"downloadProgress-->%@",downloadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功返回数据 根据responseSerializer 返回不同的数据格式
        NSLog(@"responseObject-->%@",responseObject);
        
        dispatch_async(dispatch_get_main_queue(), ^{
         
            if (success) {
                success(responseObject);
            }
            
            
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        if (failure) {
            failure(error);
        }
        
        
        
    }];
}



+ (void)GET:(NSString *)URLString
          parameters:(id)parameters
             success:(void(^)(id result,NSString *successMessage))success
             failure:(void(^)(NSInteger code,NSString *errorMessage))failure

{
    //创建请求地址
    NSString *URLS= [NSString stringWithFormat:@"%@/%@",Url_Server,URLString];
    //构造参数
    
    //AFN管理者调用get请求方法
    [[HttpRequest sharedManager] GET:URLS parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        //返回请求返回进度
        NSLog(@"downloadProgress-->%@",downloadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功返回数据 根据responseSerializer 返回不同的数据格式
        NSLog(@"responseObject-->%@",responseObject);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([responseObject[@"code"] integerValue] == 0) {
                if (success) {
                    success(responseObject[@"result"],responseObject[@"message"]);
                }
            }else{
                if (failure) {
                    failure([responseObject[@"code"] integerValue],responseObject[@"message"]);
                }
            }
        });
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        NSLog(@"error-->%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self errorInfoDealToWithTask:task];
        });
        
        
        
    }];
}


+ (void)POST:(NSString *)URLString
           parameters:(id)parameters
              success:(void(^)(id result,NSString *successMessage))success
              failure:(void(^)(NSInteger code,NSString *errorMessage))failure
{
    //创建请求地址
    NSString *URLS= [NSString stringWithFormat:@"%@/%@",Url_Server,URLString];
    //构造参数
    
    //AFN管理者调用get请求方法
    [[self sharedManager] POST:URLS parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        //返回请求返回进度
        NSLog(@"downloadProgress-->%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功返回数据 根据responseSerializer 返回不同的数据格式
        NSLog(@"responseObject-->%@",responseObject);
        
        dispatch_async(dispatch_get_main_queue(), ^{
      
            if ([responseObject[@"code"] integerValue] == 1) {
                if (success) {
                    success(responseObject,responseObject[@"desc"]);
                }
            }else {
                if (failure) {
                    failure([responseObject[@"code"] integerValue],responseObject[@"desc"]);
                }
            }
            
     
        });
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        NSLog(@"error-->%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self errorInfoDealToWithTask:task];
        });
        
    }];
}


/**
 初始化配置接口，这个借口需要网络状态

 @param URLString URLString description
 @param parameters parameters description
 @param success success description
 @param failure failure description
 */
+ (void)POST:(NSString *)URLString
  parameters:(id)parameters
     success:(void(^)(id result,NSString *successMessage))success
     failure:(void(^)(NSInteger code,NSString *errorMessage))failure
       errors:(void(^)(NSError * _Nonnull error))errors
{
    //创建请求地址
    NSString *URLS= [NSString stringWithFormat:@"%@/%@",Url_Server,URLString];
    //构造参数
    
    //AFN管理者调用get请求方法
    [[self sharedManager] POST:URLS parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        //返回请求返回进度
        NSLog(@"downloadProgress-->%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功返回数据 根据responseSerializer 返回不同的数据格式
        NSLog(@"responseObject-->%@",responseObject);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if ([responseObject[@"code"] integerValue] == 1) {
                if (success) {
                    success(responseObject,responseObject[@"desc"]);
                }
            }else {
                if (failure) {
                    failure([responseObject[@"code"] integerValue],responseObject[@"desc"]);
                }
            }
            
            
        });
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        NSLog(@"error-->%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
//            [self errorInfoDealToWithTask:task];
            
            if (errors) {
                errors(error);
            }
        });
        
    }];
}


+ (void)UPLOAD_IMAGE:(NSString *)URLString parameters:(NSDictionary*)parameters imagesArray:(NSArray *)imagesArray name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType uploadProgress:(void(^)( NSProgress * _Nonnull uploadProgress))progress
             success:(void(^)(id result,NSString *successMessage))success
             failure:(void(^)(NSInteger code,NSString *errorMessage))failure{
    
    //创建请求地址
    NSString *URLS= [NSString stringWithFormat:@"%@/%@",Url_Server,URLString];
    
    
    // 上传图片
    [[HttpRequest sharedManager] POST:URLS parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        /**
         执行这个方法时， name：部分是服务器用来解析的字段， 而fileName则是直接上传上去的图片， 注意一定要加 .jpg或者.png，（这个根据你得到这个imgData是通过jepg还是png的方式来获取决定）。 然后mimeType值也要与上面的类型对应， 网上看到有的说直接写成 @"image/"， 据说也是可以的， 没验证过。
         */
        [imagesArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [formData appendPartWithFileData:UIImageJPEGRepresentation(obj, 0.5) name:name fileName:[NSString stringWithFormat:@"%@%lu.jpg",fileName,(unsigned long)idx] mimeType:mimeType];
            
        }];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        if (progress){
            progress(uploadProgress);
        }
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSDictionary *object = [NSJSONSerialization JSONObjectWithData:responseObject
//                                                               options:0 error:nil];
        
        //请求成功返回数据 根据responseSerializer 返回不同的数据格式
        NSLog(@"responseObject-->%@",responseObject);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([responseObject[@"code"] integerValue] == 0) {
                if (success) {
                    success(responseObject[@"result"],responseObject[@"message"]);
                }
            }else{
                if (failure) {
                    failure([responseObject[@"code"] integerValue],responseObject[@"message"]);
                }
            }
        });
       
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        
        //请求失败
        NSLog(@"error-->%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self errorInfoDealToWithTask:task];
        });
        
    }];
    
}

@end
